package com.sinochem.yunlian.ship.common.handler;

import com.sinochem.yunlian.ship.common.enums.ResponseCode;
import com.sinochem.yunlian.ship.common.exception.BaseException;
import com.sinochem.yunlian.ship.common.msg.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by ace on 2017/9/8.
 */
@ControllerAdvice("com.sinochem.yunlian.ship")
@ResponseBody
public class GlobalExceptionHandler {
	
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
	@ExceptionHandler(BaseException.class)
    public RestResponse<String> baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        logger.info(ex.getMessage(),ex);
        return RestResponse.response(ex.getStatus(), ex.getMessage());
    }
	
	@ExceptionHandler(RuntimeException.class)
    public RestResponse<String> runtimeExceptionHandler(HttpServletResponse response, RuntimeException rex) {
        logger.info(rex.getMessage(),rex);
        return RestResponse.response(ResponseCode.SYS_EXCEPTION.getCode(), ResponseCode.SYS_EXCEPTION.getName());
    }

	@ExceptionHandler(Exception.class)
    public RestResponse<String> otherExceptionHandler(HttpServletResponse response, Exception ex) {
        logger.error(ex.getMessage(),ex);
        return RestResponse.response(ResponseCode.SYS_EXCEPTION.getCode(), ResponseCode.SYS_EXCEPTION.getName());
    }
    
    /**
     * @Descript
     *
     * @Date 2017年12月16日
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)  
    public RestResponse<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        StringBuilder sBuilder = new StringBuilder();
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
        	sBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage());
        	sBuilder.append(";");
        }
        logger.info(String.format("传输的参数无效:%s", sBuilder.toString()));
        return RestResponse.response(ResponseCode.INVALID_PARAM.getCode(), sBuilder.toString());  
    }  
      
    /**
     * 
     * @Descript
     *
     * @Date 2017年12月16日
     */
	@ExceptionHandler(HttpMessageNotReadableException.class)  
    public RestResponse<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
		logger.info(String.format("序列化或反序列化对象出错了:%s", ex.getRootCause().getMessage()));
        return RestResponse.response(ResponseCode.MESSAGE_NOET_READABLE.getCode(),ex.getRootCause().getMessage());  
    }

}